package com.hmdp.service.impl;

import com.hmdp.dto.Result;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.concurrent.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Resource
    private ISeckillVoucherService seckillVoucherService;
    @Resource
    private RedisIdWorker redisIdWorker;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private RedissonClient redissonClient;

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024*1024);
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    @PostConstruct
    private void init(){//类初始化后就执行
        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler());
    }
    private class VoucherOrderHandler implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    VoucherOrder voucherOrder = orderTasks.take();
                    handlerVoucherOrder(voucherOrder);
                } catch (Exception e) {
                    log.error("处理订单异常",e);
                }
            }

        }
    }

    private void handlerVoucherOrder(VoucherOrder voucherOrder) {
        /*Long userId = UserHolder.getUser().getId()为什么不用这个取出userId？
        因为 VoucherOrderHandler 是在独立线程中运行的，
        UserHolder 通常基于 ThreadLocal 实现，在异步线程中无法获取到原请求线程中的用户上下文，
        可能导致 userId 为 null 或获取到错误的用户信息。
         */
        Long userId = voucherOrder.getUserId();
        RLock lock = redissonClient.getLock("order:" + userId);
        boolean isLock = lock.tryLock();//跟业务执行时间有关
        if(!isLock){//获取锁失败
            log.error("不允许重复下单！");
            return;
        }
        try {
           proxy.createVoucherOrder(voucherOrder);
        }finally {
            lock.unlock();
        }

    }

    /**
     * lua脚本实现抢购
     * @param voucherId
     * @return
     */
    private IVoucherOrderService proxy;
    @Override
    public Result seckillVoucher(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        //判断操作放到redis中，有lua脚本获得结果
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString()
        );
        int r = result.intValue();
        if (r!=0){ //无法购买
            return Result.fail(r == 1 ? "库存不足！":"不能重复下单！");
        }
        //下单，把下单信息保存到阻塞队列中
        long orderId = redisIdWorker.nextId("order");
        //保存阻塞队列
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(userId);
        voucherOrder.setVoucherId(voucherId);
        orderTasks.add(voucherOrder);
        proxy = (IVoucherOrderService) AopContext.currentProxy();//防止事务失失效
        //返回订单id
        return Result.ok(orderId);
    }

    /**
    @Override
    public Result seckillVoucher(Long voucherId) {
        //查询
        SeckillVoucher voucher = seckillVoucherService.getById(voucherId);

        //判断秒杀时间
        if (voucher.getBeginTime().isAfter(LocalDateTime.now())) {
            return Result.fail("秒杀尚为开始！");
        }
        if (voucher.getEndTime().isBefore(LocalDateTime.now())) {
            return Result.fail("秒杀已经结束！");
        }
        //判断库存
        if (voucher.getStock()<1){
            return Result.fail("库存不足！");
        }

        Long userId = UserHolder.getUser().getId();
//        synchronized (userId.toString().intern()) {//确保值一样时，锁就一样, intern():如果创建的字符串对象在常量池中有，那么就不会在堆中创建新的String对象
//            //获取代理对象（事务）
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();//防止事务失失效
//            return proxy.createVoucherOrder(voucherId);
//            //在这加锁的好处是：最后先提交事务，再释放锁，防止事务（数据库）还没修改，下一个请求就得到锁了
//        }
//
        RLock lock = redissonClient.getLock("order:" + userId);
        boolean isLock = lock.tryLock();//跟业务执行时间有关
        if(!isLock){//获取锁失败
            return Result.fail("一个人只能下一单！");
        }
        try {
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();//防止事务失失效
            return proxy.createVoucherOrder(voucherId);
        }finally {
            lock.unlock();
        }


        ///分布式锁防止一人同时多单
        //       SimpleRedisLock lock = new SimpleRedisLock("order:" + userId,stringRedisTemplate);
//        boolean isLock = lock.tryLock(1200L);//跟业务执行时间有关
//        if(!isLock){//获取锁失败
//            return Result.fail("一个人只能下一单！");
//        }
//        try {
//            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();//防止事务失失效
//            return proxy.createVoucherOrder(voucherId);
//        }finally {
//            lock.unlock();
//        }

    }**/

    @Transactional
    public void createVoucherOrder(VoucherOrder voucherOrder) {
        //一人一单
        Long userId = voucherOrder.getUserId();
        int count = query().eq("user_id", userId)
                    .eq("voucher_id", voucherOrder.getVoucherId()).count();
        //扣减库存
        Boolean success = seckillVoucherService.update()
                .setSql("stock = stock - 1")
                .eq("voucher_id", voucherOrder.getVoucherId())
                .gt("stock",0) //乐观锁CAS防止超卖
                .update();
        save(voucherOrder);
        }
}
